import requests
from datetime import datetime , timedelta
class TTDB:
    def __init__(self):
        pass
    @staticmethod
    def write2TDB( host , port , token , db , datapointStr, rp=""):
        res = None
        try:
            '''
            host = self.tdbSettings['host']
            port = self.tdbSettings['port']
            token = self.tdbSettings['token']
            db = self.tdbSettings['db']
            '''
            headers = {
                "Authorization": token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + host + ":" + str(port) + '/write?db=' + db
            if rp != '':
                influxdb_url = influxdb_url + '&rp=rePolicy_1h'
            res = requests.post(url=influxdb_url, headers=headers, data=datapointStr)
            #print('save to tdb:', resp)
        except Exception as er:
            print(er)
        return  res
    @staticmethod
    def tdbQuerySuccess( queryResult):
        res = 0
        try:
            if( 'results' in queryResult.keys() and len(queryResult['results'])>0 ):
                if ('series' in  (queryResult['results'][0]).keys() ):
                    res = len(queryResult['results'][0]['series'])
        except Exception as er:
            print('tdb query success fail')
        return  res
    @staticmethod
    def tdbQuerySeries( queryResult):
        res = []
        try:
            series = queryResult['results'][0]['series']
            for ser in series:
                dictCol = ser['columns']
                item = [dict(zip(dictCol , x)) for x in ser['values']]
                res.append(item)
        except Exception as er:
            print('tdb query success fail')
        return  res
